from collections import deque
def bfs(i,j,grid,visited,m,n):
    que=deque([(i,j)])
    k=0
    while len(que)>0:
        l=len(que)
        for _ in range(l):
            cur=que.popleft()
            x,y=cur[0],cur[1]
            if grid[x][y]==2: return k
            for d in [(-1,0),(1,0),(0,-1),(0,1)]:
                newx,newy=x+d[0],y+d[1]
                if newx>=0 and newx<m and newy>=0 and newy<n and grid[newx][newy]!=0 and (not visited[newx][newy]):
                    visited[newx][newy]=True 
                    que.append((newx,newy))
        k+=1
    return -1

def solve(grid):
    m,n=len(grid),len(grid[0])
    ans=0
    for i in range(m):
        for j in range(n):
            if grid[i][j]==1:
                visited=[[False]*n for _ in range(m)]
                visited[i][j]=True 
                t=bfs(i,j,grid,visited,m,n)
                #print(i,j,t)
                if t==-1: return -1 
                ans=max(ans,t)
    return ans 

#grid = [[2,1,1],[1,1,0],[0,1,1]]
#grid=[[2,1,1],[0,1,1],[1,0,1]]
grid=[]
while True:
    tmp=[eval(i) for i in input().split()]
    if len(tmp)==0: break 
    grid.append(tmp)

print(solve(grid))
































# def bfs(grid,visited,que):
#     m,n=len(grid),len(grid[0])
#     k=0
#     while len(que)>0:
#         l=len(que)
#         for _ in range(l):
#             r,c=que[0][0],que[0][1]
#             if grid[r][c]==2: return k 
#             visited[r][c]=True #这里再访问
#             for d in [(-1,0),(1,0),(0,-1),(0,1)]:
#                 newi,newj=r+d[0],c+d[1] #bfs的r和c都是首个元素决定的，不是传进来的参数i和j
#                 if newi>=0 and newi<m and newj>=0 and newj<n and grid[newi][newj]!=0 and (not visited[newi][newj]):
#                     que.append((newi,newj))
#             que.remove(que[0])
#         k+=1
#     return -1 


# def solve(grid):
#     m,n=len(grid),len(grid[0])
#     ans=-1
#     for i in range(m):
#         for j in range(n):
#             if grid[i][j]==1:
#                 visited=[[0]*n for _ in range(m)]
#                 tmp=bfs(grid,visited,[(i,j)]) #先把(i,j)放进去
#                 if tmp==-1: return -1
#                 ans=max(ans,tmp)
#     return ans

# grid = [[2,1,1],[1,1,0],[0,1,1]]
# print(solve(grid))
# grid = [[2,1,1],[0,1,1],[1,0,1]]
# print(solve(grid))